package com.chenzouquan.util.format;

import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class XmlFormatter {
    public static void formatXmlFile(String xmlFilePath) {
        try {
            // 读取XML文件内容并创建Document对象
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new FileReader(xmlFilePath)));

            // 创建Transformer对象，用于格式化XML
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            // 创建DOMSource对象
            DOMSource source = new DOMSource(document);

            // 创建StreamResult对象，将格式化后的XML写入文件
            StringWriter stringWriter = new StringWriter();
            StreamResult result = new StreamResult(new BufferedWriter(stringWriter));

            // 应用格式化设置并写入文件
            transformer.transform(source, result);
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(xmlFilePath));
            bufferedWriter.write(stringWriter.toString());
            bufferedWriter.close();

            System.out.println("XML文件格式化成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

